package org.jeecg.modules.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.DeviceConstant;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SysTenantVo;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.entity.DevDeviceRecord;
import org.jeecg.modules.device.entity.DevReservoirInfo;
import org.jeecg.modules.device.service.IDevDeviceInfoService;
import org.jeecg.modules.device.service.IDevDeviceRecordService;
import org.jeecg.modules.device.service.IDevReservoirInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 水库信息表
 * @Author: jeecg-boot
 * @Date:   2024-04-17
 * @Version: V1.0
 */
@Api(tags="水库信息表")
@RestController
@RequestMapping("/device/devReservoirInfo")
@Slf4j
public class DevReservoirInfoController extends JeecgController<DevReservoirInfo, IDevReservoirInfoService> {
	@Autowired
	private IDevReservoirInfoService devReservoirInfoService;
	@Autowired
	private IDevDeviceInfoService devDeviceInfoService;
	@Autowired
	private IDevDeviceRecordService deviceRecordService;
	 @Autowired
	 private RedisUtil redisUtil;
	
	/**
	 * 分页列表查询
	 *
	 * @param devReservoirInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "水库信息表-分页列表查询")
	@ApiOperation(value="水库信息表-分页列表查询", notes="水库信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DevReservoirInfo>> queryPageList(DevReservoirInfo devReservoirInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DevReservoirInfo> queryWrapper = QueryGenerator.initQueryWrapper(devReservoirInfo, req.getParameterMap());
		Page<DevReservoirInfo> page = new Page<DevReservoirInfo>(pageNo, pageSize);
		IPage<DevReservoirInfo> pageList = devReservoirInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param devReservoirInfo
	 * @return
	 */
	@AutoLog(value = "水库信息表-添加")
	@ApiOperation(value="水库信息表-添加", notes="水库信息表-添加")
	@RequiresPermissions("device:iot_dev_reservoir_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DevReservoirInfo devReservoirInfo) {
		if(StringUtils.isEmpty(devReservoirInfo.getCode())){
			DevReservoirInfo one = devReservoirInfoService.getOne(Wrappers.<DevReservoirInfo>lambdaQuery()
					.eq(DevReservoirInfo::getDelFlag, 0)
					.orderByAsc(DevReservoirInfo::getCode).last("limit 1"));
			if(null != one){
				String code = one.getCode();
				long codeLong=Long.parseLong(code)+1;
				devReservoirInfo.setCode(codeLong+"");
			}else {
				//租户地区编号+四位顺序编号
				Object tenantObj = redisUtil.hget(TenantConstant.SYS_TENANT_CACHE_MAP, null!=TenantContext.getTenant()?TenantContext.getTenant():"0");
				if(null != tenantObj ){
					SysTenantVo tenantVo = (SysTenantVo)tenantObj;
					String address = tenantVo.getAddress();//区划编码
					if(StringUtils.isNotEmpty(address)){
						devReservoirInfo.setCode(address+"0001");
					}else{
						devReservoirInfo.setCode("00000001");
					}
				}
			}
		}
		devReservoirInfoService.save(devReservoirInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param devReservoirInfo
	 * @return
	 */
	@AutoLog(value = "水库信息表-编辑")
	@ApiOperation(value="水库信息表-编辑", notes="水库信息表-编辑")
	@RequiresPermissions("device:iot_dev_reservoir_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DevReservoirInfo devReservoirInfo) {
		if(StringUtils.isEmpty(devReservoirInfo.getCode())){
			DevReservoirInfo one = devReservoirInfoService.getOne(Wrappers.<DevReservoirInfo>lambdaQuery()
					.eq(DevReservoirInfo::getDelFlag, 0)
					.ne(DevReservoirInfo::getId,devReservoirInfo.getId())
					.orderByAsc(DevReservoirInfo::getCode).last("limit 1"));
			if(null != one){
				String code = one.getCode();
				long codeLong=Long.parseLong(code)+1;
				devReservoirInfo.setCode(codeLong+"");
			}else {
				//租户地区编号+四位顺序编号
				Object tenantObj = redisUtil.hget(TenantConstant.SYS_TENANT_CACHE_MAP, null!=TenantContext.getTenant()?TenantContext.getTenant():"0");
				if(null != tenantObj ){
					SysTenantVo tenantVo = (SysTenantVo)tenantObj;
					String address = tenantVo.getAddress();//区划编码
					if(StringUtils.isNotEmpty(address)){
						devReservoirInfo.setCode(address+"0001");
					}else{
						devReservoirInfo.setCode("00000001");
					}
				}
			}
		}
		devReservoirInfoService.updateById(devReservoirInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "水库信息表-通过id删除")
	@ApiOperation(value="水库信息表-通过id删除", notes="水库信息表-通过id删除")
	@RequiresPermissions("device:iot_dev_reservoir_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		devReservoirInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "水库信息表-批量删除")
	@ApiOperation(value="水库信息表-批量删除", notes="水库信息表-批量删除")
	@RequiresPermissions("device:iot_dev_reservoir_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.devReservoirInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "水库信息表-通过id查询")
	@ApiOperation(value="水库信息表-通过id查询", notes="水库信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DevReservoirInfo> queryById(@RequestParam(name="id",required=true) String id) {
		DevReservoirInfo devReservoirInfo = devReservoirInfoService.getById(id);
		if(devReservoirInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(devReservoirInfo);
	}



    /**
    * 导出excel
    *
    * @param request
    * @param devReservoirInfo
    */
    @RequiresPermissions("device:iot_dev_reservoir_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DevReservoirInfo devReservoirInfo) {
        return super.exportXls(request, devReservoirInfo, DevReservoirInfo.class, "水库信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("device:iot_dev_reservoir_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DevReservoirInfo.class);
    }


	 /**
	  * 获取水库列表查询
	  *
	  * @param devReservoirInfo
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "水库信息表-分页列表查询")
	 @ApiOperation(value="水库信息表-列表查询", notes="水库信息表-列表查询")
	 @GetMapping(value = "/api/getList")
	 public Result<List<DevReservoirInfo>> getList(DevReservoirInfo devReservoirInfo,HttpServletRequest req) {
		 QueryWrapper<DevReservoirInfo> queryWrapper = QueryGenerator.initQueryWrapper(devReservoirInfo, req.getParameterMap());
		 List<DevReservoirInfo> list = devReservoirInfoService.list(queryWrapper);
		 return Result.OK(list);
	 }

	/**
	 * 根据水库获取设备列表-数据
	 * @param reservoirId
	 * @return
	 */
	//@AutoLog(value = "水库信息表-分页列表查询")
	@ApiOperation(value="根据水库获取设备列表-数据", notes="根据水库获取设备列表-数据")
	@GetMapping(value = "/api/getDeviceList/{reservoirId}")
	public Result<JSONArray> getDeviceList(@PathVariable("reservoirId") String reservoirId) {
		List<DevDeviceInfo> list = devDeviceInfoService.list(Wrappers.<DevDeviceInfo>lambdaQuery()
				.eq(DevDeviceInfo::getDelFlag,0).eq(DevDeviceInfo::getReservoirId,reservoirId));

		// 当前租户
		String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");

		JSONArray recordVoLs = new JSONArray();

		for (DevDeviceInfo deviceInfo : list) {

			/**3.缓存设备数据*/
			JSONObject map = (JSONObject) redisUtil.hget(DeviceConstant.DEVICE_REALTIME_DATA+"::"+
					tenantId, deviceInfo.getDeviceId());

			if(null != map && map.size()>0){
				recordVoLs.add(map);
			}else{
				DevDeviceRecord deviceRecord = deviceRecordService.getOne(Wrappers.<DevDeviceRecord>lambdaQuery()
						.eq(DevDeviceRecord::getDeviceId, deviceInfo.getDeviceId())
						.eq(DevDeviceRecord::getDelFlag, 0)
						.orderByDesc(DevDeviceRecord::getUpdateTime)
						.last(" limit 1"));

				JSONObject hashMap = JSON.parseObject(JSON.toJSONString(deviceRecord), JSONObject.class);
				recordVoLs.add(hashMap);
			}
		}
		return Result.OK(recordVoLs);
	}
}
